/**
 * @name ChatRoom
 * @desc 聊天室界面
 * @author darcrand
 * @version 2018-10-15
 */

import React, { Component } from 'react'
import io from 'socket.io-client'
import ChatItem from '@/components/ChatItem'
import ChatInput from '@/components/ChatInput'
import './styles.scss'

let socket = null
const roomUrl = 'http://192.168.166.16:8088/chat-room'

class ChatRoom extends Component {
    static defaultProps = {
        userInfo: { id: '', name: '', avatar: '' }
    }

    state = { messageList: [] }

    componentDidMount() {
        socket = io.connect(roomUrl)
        socket.on('server-message', res => {
            const last = this.state.messageList[this.state.messageList.length - 1]
            const shouldShowDate = !last || res.date - last.date > 30000
            const data = { ...res, shouldShowDate }
            this.setState(pre => ({ messageList: [...pre.messageList, data] }))
        })
    }

    componentDidUpdate(preProps, preState) {
        if (preState.messageList.length !== this.state.messageList.length) {
            const eleScroll = this.refs.messages
            eleScroll.scrollTo(0, eleScroll.scrollHeight)
        }
    }

    onSendMessage = message => {
        const date = new Date().getTime()
        const id = this.props.userInfo.id + date
        socket.emit('client-message', {
            userInfo: this.props.userInfo,
            id,
            date,
            message
        })
    }

    render() {
        const { messageList } = this.state

        return (
            <div classes="container">
                <div classes="top-bar">The Chat Room.</div>
                <ul classes="message-list" ref="messages">
                    {messageList.map(v => (
                        <ChatItem key={v.id} {...v} currUserId={this.props.userInfo.id} />
                    ))}
                </ul>
                <ChatInput onSend={this.onSendMessage} />
            </div>
        )
    }
}

export default ChatRoom
